/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.viajarfacil.DAO;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import com.viajarfacil.util.HibernateUtil;

/**
 *
 * @author Felizardo
 */
public class GenericHibDAO<T, I extends Serializable> {
    private Session session;
    private Class<T> persistentClass;
     
   @SuppressWarnings("unchecked")
    public GenericHibDAO() {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        persistentClass =  (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
   
    @SuppressWarnings("unchecked")
    public T get(I id) {
        return (T)session.get(persistentClass, id);
    }
    
    @SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        Example example =  Example.create(exampleInstance);
        for (String exclude : excludeProperty) {
            example.excludeProperty(exclude);
        }
        crit.add(example);
        return crit.list();
    }
    
    public void remove(T entity) {
        getSession().delete(entity);
    }
 
    public List<T> findAll() {
        return findByCriteria();
    }
    
    public T saveOrUpdate(T entity) {
        getSession().saveOrUpdate(entity);
        return entity;
    }
    
    public void flush() {
        getSession().flush();
    }
 
    public void clear() {
        getSession().clear();
    }
     /**
     * Use this inside subclasses as a convenience method.
     */
    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
            crit.add(c);
        }
        return crit.list();
    }
    protected Session getSession() {
        if (session == null)
            throw new IllegalStateException("Session has not been set on DAO before usage");
        return session;
    }
    protected Class<T> getPersistentClass() {
        return persistentClass;
    }
}
